/**
 * @Author: jbt
 * @Date:   2017-02-28T11:26:55+08:00
 * @Email:  947809647@qq.com
 * @Last modified by:   liutao
 * @Last modified time: 2017-04-25T14:21:51+08:00
 */
import Resource from 'vue-resource'
import { showLoading, hideLoading } from '../util/loading'

const TIME_OUT = 300 * 1000

export default function useResource(Vue) {
  Vue.use(Resource)

  // HTTP相关
  Vue.http.options.crossOrigin = true
  Vue.http.options.emulateJSON = true
  Vue.http.options.credentials = false
  Vue.http.interceptors.push((req, next) => {
    let timeoutTicker = setTimeout(() => {
      hideLoading()
      next(req.respondWith({}, {
        status: 'timeout',
        statusText: 'timeout'
      }))
      req.abort()
    }, TIME_OUT)

    showLoading()

    // if (req.method === 'GET') {
    //   req.method = 'POST'
    //   req.body = req.params
    //   req.params = {}
    // }
    req.params._ = Date.now()

    next((res) => {
      clearTimeout(timeoutTicker)
      hideLoading()
      if (!res.ok) {
        res.ok = true
        res.status = 200
        res.data = {
          code: '-1',
          error_msg: '系统或网络错误'
        }
      } else {
        try {
          res.data = JSON.parse(res.data)
        } catch ( e ) {}
      }
    })
  })
}
